﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using fKanban.Model;
using fKanban.Provider;
using fKanban.Utility.ObjectExtend;

namespace vancldashboard.Controllers
{
    public class OnlineController : Controller
    {
        UserStoryProvider userStoryProvider = new UserStoryProvider();
        SprintProvider sprintProvider = new SprintProvider();
        SprintGoalProvider sprintGoalProvider = new SprintGoalProvider();
        SprintTaskProvider sprintTaskProvider = new SprintTaskProvider();
        UserProvider userProvider = new UserProvider();

        public ActionResult fKanban(int id = 1, int userStoryId = 0, int sprintId = 0)
        {
            ViewBag.Title = "需求池管理 Dashboard Manage";
            ViewData["Id"] = this.Id = id;
            ViewData["userStoryId"] = userStoryId;
            ViewData["sprintId"] = sprintId;

            //kanban
            if (id > 0 && userStoryId > 0 && sprintId > 0)
            {
                var goals = sprintGoalProvider.LoadData(new SprintGoalEntity() { SprintId = sprintId });
                {
                    if (null != goals)
                    {
                        foreach (var goalEntity in goals)
                        {
                            goalEntity.Tasks = sprintTaskProvider.LoadData(new SprintTaskEntity() { GoalId = goalEntity.Id });
                            if (goalEntity.Tasks == null || goalEntity.Tasks.Count <= 0)
                                continue;
                            goalEntity.Todos = goalEntity.Tasks.Where(x => x.Status == 1).ToList();
                            goalEntity.Doings = goalEntity.Tasks.Where(x => x.Status == 2).ToList();
                            goalEntity.Dones = goalEntity.Tasks.Where(x => x.Status == 3).ToList();

                            goalEntity.Duration = goalEntity.Tasks.Select(x => x.Duration).Sum();//实际进度
                            goalEntity.DurationToDo = goalEntity.Todos.Select(x => x.Duration).Sum();//Todos
                            goalEntity.DurationDoing = goalEntity.Doings.Select(x => x.Duration).Sum();//Doings
                            goalEntity.DurationDone = goalEntity.Dones.Select(x => x.Duration).Sum();//Dones
                        }
                        ViewData["totalDuration"] = goals.Select(x => x.Duration).Sum();
                        ViewData["authorDuration"] = goals.SelectMany(x => x.Tasks)
                            .GroupBy(x => x.Author)
                            .ToDictionary(x => x.Key, x => x.Select(o => o.Duration).Sum());
                    }
                }
                ViewData["goals"] = goals;
                ViewBag.Title = "看板管理 Kanban Manage";
                ViewData["navParent"] = "<<";
                ViewData["nav"] = string.Format("{0}/{1}/", id, userStoryId);
                return View("Kanban");
            }
            //sprint
            if (id > 0 && userStoryId > 0)
            {
                var sprints = sprintProvider.LoadData(new SprintEntity() { UserStoryId = userStoryId });
                {
                    foreach (var item in sprints)
                    {
                        DateTime dtBegin = item.StartDate;
                        DateTime dtEnd = item.EndDate;
                        item.Duration = (dtEnd - dtBegin).Days + 1;
                        item.DatePassed = (DateTime.Now - dtBegin).Days + 1;
                        item.DateLeft = item.Duration - item.DatePassed;
                        item.Progress = string.Format("(第{0}/{1}天)", item.DatePassed, item.Duration);
                        if (item.DatePassed > item.Duration)
                        {
                            item.DatePassed = item.Duration;
                            item.DateLeft = 0;
                            item.Progress = string.Format("周期({0}天)", item.Duration);
                        }
                        item.ProgressValue = (int)(0.5 + 100.0 * (item.DatePassed * 1.0 / item.Duration * 1.0));
                        item.ProgressLength = item.ProgressValue * 3;
                    }

                    ViewData["sprints"] = sprints;
                    ViewData["userStory"] = userStoryProvider.LoadDataById(new UserStoryEntity() { Id = userStoryId });
                }

                ViewBag.Title = "迭代管理 Sprint Manage";
                ViewData["navParent"] = "<<";
                ViewData["nav"] = string.Format("{0}/", id);

                return View("Sprint") ;
            }
            if (id > 0)
            {
                ViewBag.Title = this.IsAuthenticated ? "需求池管理 Product Backlog Manage" : "需求池 Product Backlog";
                ViewData["navParent"] = "";
                ViewData["nav"] = "";
                ViewData["userStories"] = userStoryProvider.LoadData(id);
                return View();
            }

            //团队列表
            ViewBag.Title = "团队列表Teamlist";
            ViewData["nav"] = "";
            ViewData["navParent"] = "";
            return View("DashboardList");
        }
        //管理模式
        public ActionResult Kanban(int id)
        {
            return View();
        }
        public ActionResult Sprint(int id)
        {
            return View();
        }

        public ActionResult Manage()
        {
            ViewBag.Title = "需求池UserStories";
            ViewData["navParent"] = "<<";
            ViewData["nav"] = "fKanban/";
            return View();
        }
        public ActionResult Register()
        {
            ViewBag.Title = "创建数据库Create Database";
            return View();
        }

        public PartialViewResult KanbanRowTemplateControl()
        {
            return PartialView();
        }
        public PartialViewResult KanbanItemTemplateControl()
        {
            return PartialView();
        }
        
        #region UserStory
        public PartialViewResult UserSotryAddControl()
        {
            return PartialView();
        }
        [HttpPost]
        public ActionResult AddUserStory(UserStoryEntity entity)
        {
            try
            {
                var userStoryId = userStoryProvider.Add(entity);
                return Json(new
                {
                    Message = "ok",
                    IsAuthenticated = IsAuthenticated,
                    Id = userStoryId,
                    rowsAffected = 1
                });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult UpdateUserStory(UserStoryEntity entity)
        {
            try
            {
                var userStoryId = userStoryProvider.Update(entity);
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Id = userStoryId, rowsAffected = 1 });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult RemoveUserStory(int id)
        {
            try
            {
                var rowsAffected = userStoryProvider.Remove(new UserStoryEntity(id));
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, rowsAffected = rowsAffected });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult LoadUserStories()
        {
            try
            {
                var re = userStoryProvider.LoadData();
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Result = re, rowsAffected = re.Count });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult LoadUserStoryById(int id)
        {
            try
            {
                var userStory = userStoryProvider.LoadDataById(new UserStoryEntity(id));
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Result = userStory, Id = id, rowsAffected = 1 });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        #endregion

        #region Sprint
        public PartialViewResult SprintAddControl()
        {
            return PartialView();
        }
        [HttpPost]
        public ActionResult AddSprint(SprintEntity entity)
        {
            try
            {
                var sprintId = sprintProvider.Add(entity);
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Id = sprintId, rowsAffected = 1 });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult UpdateSprint(SprintEntity entity)
        {
            try
            {
                var sprintId = sprintProvider.Update(entity);
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Id = sprintId, rowsAffected = 1 });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult RemoveSprint(int id)
        {
            try
            {
                var rowsAffected = sprintProvider.Remove(new SprintEntity(id));
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, rowsAffected = rowsAffected });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult LoadSprintsByUserStoryId(int userStoryId)
        {
            try
            {
                var re = sprintProvider.LoadData(new SprintEntity(userStoryId));
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Result = re, rowsAffected = re.Count });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult LoadSprints()
        {
            try
            {
                var re = sprintProvider.LoadData();
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Result = re, rowsAffected = re.Count });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult LoadSprintById(int id)
        {
            try
            {
                var sprintEntity = sprintProvider.LoadDataById(new SprintEntity(id));
                return Json(new { Message = "ok", Result = sprintEntity, Id = id });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        #endregion

        #region SprintGoal
        public PartialViewResult GoalAddControl()
        {
            return PartialView();
        }
        [HttpPost]
        public ActionResult AddSprintGoal(SprintGoalEntity entity)
        {
            try
            {
                var sprintGoalId = sprintGoalProvider.Add(entity);
                return Json(new
                {
                    message = "ok",
                    insertedId = sprintGoalId,
                    rowsAffected = 1
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult UpdateSprintGoal(SprintGoalEntity entity)
        {
            try
            {
                var rowsAffected = sprintGoalProvider.Update(entity);
                return Json(new
                {
                    message = "ok",
                    insertedId = 0,
                    rowsAffected = rowsAffected
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult RemoveSprintGoal(int id)
        {
            try
            {
                var rowsAffected = sprintGoalProvider.Remove(new SprintGoalEntity(id));
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, rowsAffected = rowsAffected });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        [HttpPost]
        public ActionResult LoadSprintGoalsBySprintId(int sprintId)
        {
            try
            {
                var re = sprintGoalProvider.LoadData(new SprintGoalEntity() { SprintId = sprintId });
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Result = re, rowsAffected = re.Count });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }

        [HttpPost]
        public ActionResult LoadSprintGoalById(int id)
        {
            try
            {
                var sprintGoal = sprintGoalProvider.LoadData(new SprintGoalEntity(id));
                return Json(new { Message = "ok", IsAuthenticated = IsAuthenticated, Result = sprintGoal });
            }
            catch (Exception exp)
            {
                return Json(new { Message = exp.Message });
            }
        }
        #endregion

        #region SprintTask
        public PartialViewResult TaskAddControl()
        {
            return PartialView();
        }
        [HttpPost]
        public ActionResult AddSprintTask(SprintTaskEntity entity)
        {
            try
            {
                var sprintTaskId = sprintTaskProvider.Add(entity);
                return Json(new
                {
                    message = "ok",
                    insertedId = sprintTaskId,
                    rowsAffected = 1
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult RemoveSprintTask(int id)
        {
            try
            {
                var rowsAffected = sprintTaskProvider.Remove(new SprintTaskEntity(id));
                return Json(new
                {
                    message = "ok",
                    insertedId = 0,
                    rowsAffected = rowsAffected
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult UpdateSprintTask(SprintTaskEntity entity)
        {
            try
            {
                var rowsAffected = sprintTaskProvider.Update(entity);
                return Json(new
                {
                    message = "ok",
                    insertedId = 1,
                    rowsAffected = rowsAffected
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult LoadSprintTasksBySprintGoalId(int sprintGoalId)
        {
            try
            {
                var re = sprintTaskProvider.LoadData(new SprintTaskEntity() { GoalId = sprintGoalId });
                return Json(new
                {
                    message = "ok",
                    insertedId = 0,
                    rowsAffected = re.Count,
                    result = re,
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult LoadSprintTasks()
        {
            try
            {
                var re = sprintTaskProvider.LoadData(new SprintTaskEntity());
                return Json(new
                {
                    message = "ok",
                    insertedId = 0,
                    rowsAffected = re.Count,
                    result = re,
                });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        [HttpPost]
        public ActionResult LoadSprintTaskById(int id)
        {
            try
            {
                var sprintTask = sprintTaskProvider.LoadData(new SprintTaskEntity(id));
                return Json(new { message = "ok", IsAuthenticated = IsAuthenticated, Result = sprintTask });
            }
            catch (Exception exp)
            {
                return Json(new
                {
                    message = "err:" + exp.Message,
                    insertedId = 0,
                    rowsAffected = 0
                });
            }
        }
        #endregion

        #region Users
        public ActionResult Users(int id = 0)
        {
            ViewBag.Title = "用户列表Users";
            ViewData["navParent"] = "<<";
            ViewData["nav"] = "Users/";
            return View(userProvider.GetUserByPara(new UserEntity(id)) ?? new List<UserEntity> { new UserEntity() });
        }
        #endregion

        #region Utility
        public int Id { get; set; }
        public bool IsAuthenticated
        {
            get
            {
                return true;
            }
        }
        #endregion
    }
}

//http://www.cnblogs.com/abllyboy/archive/2011/02/18/1958134.html
